package com.netwrok;

import java.nio.ByteBuffer;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.LinkedBlockingQueue;

import com.ex.common.ObjectPool;
import com.netwrok.mem.IoEventPool;

public class IoQueues {
	private static IoQueues object = new IoQueues();

	private IoQueues() {
	}

	public static IoQueues getInstance() {
		return object;
	}

	private LinkedBlockingQueue<IoEvent> events = new LinkedBlockingQueue<IoEvent>();

	public IoEvent getIoEvent() {
		try {
			return events.take();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void addNewSession(IoSession session, NetworkEvents network) {
		ObjectPool<IoEvent> pool = IoEventPool.getPool();
		IoEvent event = pool.alloc();
		event.reset(IoEvent.Type_Net_New, session, null, network);
		events.add(event);
	}

	public void addCloseSession(IoSession session, NetworkEvents network) {
		ObjectPool<IoEvent> pool = IoEventPool.getPool();
		IoEvent event = pool.alloc();
		event.reset(IoEvent.Type_Net_Cls, session, null, network);
		events.add(event);
	}

	public void addMsg(IoSession session, RequestMsg msg, NetworkEvents network) {
		ObjectPool<IoEvent> pool = IoEventPool.getPool();
		IoEvent event = pool.alloc();
		event.reset(IoEvent.Type_Msg_Rcv, session, msg, network);
		events.add(event);
	}

	private ConcurrentHashMap<IoSession, ConcurrentLinkedQueue<ByteBuffer>> response = new ConcurrentHashMap<IoSession, ConcurrentLinkedQueue<ByteBuffer>>();

	void registSession4Response(IoSession session) {
		response.put(session, new ConcurrentLinkedQueue<ByteBuffer>());
	}

	public void removeSession4Response(IoSession session) {
		ConcurrentLinkedQueue<ByteBuffer> responses = response.remove(session);
		if (responses == null) {
			return;
		}
		responses.clear();
	}

	public void addResponse(IoSession session, ByteBuffer msg) {
		ConcurrentLinkedQueue<ByteBuffer> resp = response.get(session);
		resp.add(msg);
	}

	public ConcurrentLinkedQueue<ByteBuffer> getResponse(IoSession session) {
		return response.get(session);
	}

}
